package com.allsofts.algorithm.easy;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: pattern
 * @Package: com.allsofts.algorithm.easy
 * @description:
 * @Author: liyc
 * @CreateDate: 2019/1/16 4:37 PM
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2019</p>
 */
public class AddTwoNumbers {
    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        StringBuffer l1Str = new StringBuffer();
        StringBuffer l2Str = new StringBuffer();
        while (l1 != null) {
            l1Str.append(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            l2Str.append(l2.val);
            l2 = l2.next;
        }
        char[] oneArr = l1Str.toString().toCharArray();
        char[] twoArr = l2Str.toString().toCharArray();
        int len = oneArr.length > twoArr.length ? oneArr.length : twoArr.length;
        boolean add = false;
        StringBuffer sumStr = new StringBuffer();
        for (int i = 0; i < len; i++) {
            int one = 0;
            if (i < oneArr.length){
                one = oneArr[i] - 48;
            }
            int two = 0;
            if (i < twoArr.length){
                two = twoArr[i] - 48;
            }
            int sum;
            if (add) {
                sum = one + two + 1;
            } else {
                sum = one + two;
            }
            if (sum >= 10) {
                add = true;
                sumStr.append(sum - 10);
            }else {
                add = false;
                sumStr.append(sum);
            }
        }
        //最后一位的1
        if (add){
            sumStr.append(1);
        }
        char[] arrays = sumStr.toString().toCharArray();
        ListNode listNode = new ListNode(arrays[0] - 48);
        ListNode tempNode = listNode;
        for (int i = 1; i < arrays.length; i++) {
            char c = arrays[i];
            ListNode node = new ListNode(c - 48);
            tempNode.next = node;
            tempNode = node;
        }
        return listNode;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l11 = new ListNode(8);
//        ListNode l12 = new ListNode(3);
        l1.next = l11;
//        l11.next = l12;

        ListNode l2 = new ListNode(0);
//        ListNode l21 = new ListNode(6);
//        ListNode l22 = new ListNode(4);
//        l2.next = l21;
//        l21.next = l22;

        addTwoNumbers(l1, l2);

    }
}
